<template>
<div class="userManage">
  <search-block>
    <template slot="button">
      <el-button type="primary" @click="search(true)">查询</el-button>
      <el-button type="primary" @click="addUser">添加用户</el-button>
    </template>
    <el-form inline :model="model" label-width="100px" @submit.native.prevent>
      <el-form-item label="账号/用户名:">
        <el-input v-model="model.searchContent"></el-input>
      </el-form-item>
    </el-form>
  </search-block>
  <y-table
    ref="table"
    border
    pagination
    :getDataWay="getDataWay"
    :columns="columns"
  >
    <el-table-column slot="status" label="是否冻结" align="center" header-align="center" width="80">
      <template v-slot="scope">
        <el-popconfirm
          :title="scope.row.status === '0' ? '是否确认冻结该用户？' : '是否确认解冻该用户？'"
          @confirm="() => {
            if(scope.row.status === '0') lockAccount(scope.row)
            else unlockAccount(scope.row);
          }"
        >
          <el-switch
            disabled
            slot="reference"
            v-model="scope.row.status"
            active-value="1"
            inactive-value="0"></el-switch>
        </el-popconfirm>
      </template>
    </el-table-column>
    <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="250">
      <template v-slot="scope">
        <div class="table-buttons">
          <el-button type="primary" size="mini" @click="linkRole(scope.row)">绑定角色</el-button>
          <el-button type="primary" size="mini" @click="editUser(scope.row)">编辑</el-button>
          <el-popconfirm
            title="是否确认删除该用户？"
            @confirm="delUser(scope.row)">
            <el-button slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
        </div>
      </template>
    </el-table-column>
  </y-table>
  <y-form
    v-model="forms.formModel"
    :visible.sync="forms.showForm"
    :title="forms.formTypeTitle[forms.formsType]"
    destroy-on-close
    width="50%"
    :form-attrs="forms.formAttrs"
    :columns="forms.formColumns"
    @ensure="ensureModel">
  </y-form>
  <y-form
    v-model="roleForms.formModel"
    :visible.sync="roleForms.showForm"
    :title="`【${roleForms.currentForm.userName}】授权角色`"
    destroy-on-close
    width="50%"
    :form-attrs="roleForms.formAttrs"
    :columns="roleForms.formColumns"
    @opened="getUserRole(roleForms.currentForm)"
    @ensure="ensureRoleModel">
    <template slot="auth">
      <el-select v-model="roleForms.formModel.auth" clearable multiple>
        <el-option
          v-for="item in roleForms.rolesList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id"></el-option>
      </el-select>
    </template>
  </y-form>
</div>
</template>

<script>
export default {
  name: "userManage",
  inject: ['pattern'],
  computed:{
    getDataWay(){
      return{
        dataType: 'url',
        data: this.$api.system.queryTenantUsers,
        param: this.model
      }
    }
  },
  data(){
    return{
      model:{
        searchContent: '',
      },
      columns: [{
        label: "登录名",
        prop: "userName",
        width: 110
      },{
        label: "真实姓名",
        prop: "realName",
        width: 90
      },{
        label: "角色",
        prop: "roleList",
        formatter({roleList}){
          return (roleList || []).map(item => item.roleName).toString();
        },
        minWidth: 120
      },{
        label: "手机号",
        prop: "mobileNum",
        width: 115
      },{
        label: "邮箱",
        prop: "email",
        minWidth: 120
      },{
        label: "是否冻结",
        prop: "status",
        template: true
      }],
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加用户',
          'EDIT': '编辑用户'
        },
        formModel:{
          userName: '',
          realName: '',
          mobileNum: '',
          email: ''
        },
        currentForm: null,
        showForm: false,
        formAttrs:{
          labelWidth: '100px',
          rules: {
            userName: [{required: true, message: "请输入登录名", trigger: "blur"}],
            realName: [{required: true, message: "请输入真实姓名", trigger: "blur"}],
            mobileNum: [
              {required: true, message: "请输入手机号码", trigger: "blur"},
              {pattern: this.pattern.phone, message: "手机号码格式不正确", trigger: "blur"}
            ],
            email: [
              {required: true, message: "请输入邮箱", trigger: "blur"},
              {pattern: this.pattern.email, message: "邮箱格式不正确", trigger: "blur"}
            ]
          }
        },
        formColumns:[
          {
            label: "登录名",
            prop: "userName",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 20,
                showWordLimit: true
              }
            }
          },{
            label: "真实姓名",
            prop: "realName",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 10,
                showWordLimit: true
              }
            }
          },{
            label: "手机号",
            prop: "mobileNum",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 11,
                showWordLimit: true
              }
            }
          },{
            label: "邮箱",
            prop: "email",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 30,
                showWordLimit: true
              }
            }
          }
        ],
      },
      roleForms:{
        formModel:{
          auth: []
        },
        currentForm: {},
        showForm: false,
        formAttrs:{
          labelWidth: '100px'
        },
        formColumns:[
          {
            label: "授权角色",
            prop: "auth",
            template: true
          }
        ],
        rolesList: []
      }
    }
  },
  mounted() {
    this.$yAxios({
      url: this.$api.system.queryRoles
    }, info => {
      this.roleForms.rolesList = info;
    });
  },
  methods:{
    resetForm(){
      Object.keys(this.forms.formModel).map(key => {
        this.forms.formModel[key] = this.forms.currentForm ? this.forms.currentForm[key] : '';
      })
    },
    addUser(){
      this.forms.formsType = 'ADD';
      this.forms.currentForm = null;
      this.resetForm();
      this.forms.showForm = true;
    },
    search(jumpToFirst){
      this.$refs['table'].loadData(this.model, jumpToFirst);
    },
    editUser(row){
      this.forms.formsType = 'EDIT';
      this.forms.currentForm = row;
      this.resetForm();
      this.forms.showForm = true;
    },
    delUser(row){
      this.$yAxios({
        url: this.$api.system.removeById,
        data:{
          id: row.id
        }
      }, info => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.search();
      })
    },
    lockAccount(row){
      this.$yAxios({
        url: this.$api.system.lockAccount,
        data:{
          id: row.id
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: `成功冻结用户【${row.realName}】`
        });
        row.status = '1';
      });
    },
    unlockAccount(row){
      this.$yAxios({
        url: this.$api.system.unlockAccount,
        data:{
          id: row.id
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: `成功解冻用户【${row.realName}】`
        });
        row.status = '0';
      });
    },
    linkRole(row){
      this.roleForms.formModel.auth = [];
      this.roleForms.currentForm = row;
      this.roleForms.showForm = true;
    },
    getUserRole({id}){
      this.$yAxios({
        url: this.$api.system.queryRolesByUserId,
        data: {
          id
        }
      }, info => {
        this.roleForms.formModel.auth = info.map(item => item.roleId)
      })
    },
    ensureModel(form){
      let newForm;
      if(this.forms.formsType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
      }else{
        newForm = Object.assign({}, form);
      }
      this.$yAxios({
        url: this.$api.system.saveOrUpdateUser,
        data: newForm
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.search(this.forms.formsType === 'ADD');
      })
    },
    ensureRoleModel(){
      this.$yAxios({
        url: this.$api.system.saveRoleUserBatch,
        data: {
          roleIds: this.roleForms.formModel.auth,
          userId: this.roleForms.currentForm.id
        }
      }, info => {
        this.$message({
          type: 'success',
          message: '绑定成功'
        });
        this.search();
      })
    }
  }
}
</script>

<style scoped>

</style>